package com.blank.task19;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class UserClient {
    public static void main(String[] args) {
        Socket s = null;
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;
        try {
            //创建Socket类型的对象并提供服务器的主机名和端口号
            s = new Socket("127.0.0.1",8080);
            System.out.println("连接服务器成功...");
            //使用输入输出流进行通信
            UserMessage um = new UserMessage("login",new User("admin","123456"));
            //ObjectOutputStream类主要用于um对象的所有内容整体写入到输出流中
            oos = new ObjectOutputStream(s.getOutputStream());
            //发出UserMessage类型的对象
            oos.writeObject(um);
            ois = new ObjectInputStream(s.getInputStream());
            um = (UserMessage) ois.readObject();
            //根据传来的状态进行判断
            if(um.getType().equals("success")){
                System.out.println("登录成功！");
            }else{
                System.out.println("登录失败！");
            }
        } catch (IOException |ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            if(null != ois){
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null != oos){
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null != s){
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
